<template>
	<view class="container">
		<view style="background-color: #FFF;">
			<orderShopCartList :itemList="orderItemList"></orderShopCartList>
		</view>
		<!-- 商品金额 -->
		<view style="background-color: #ffffff;padding: 20rpx 30rpx;margin-top: 10rpx;">
			<view class="priceRow">
				<text>商品金额</text>
				<view style="font-size: 34rpx;">¥{{$count.mul(priceModel.sellingPrice||0, 1)}}</view>
			</view>
			<view class="priceRow" v-for="(item, index) in priceModel.discountParams" :key='index'>
				<text>{{item.type}}</text>
				<view style="color: #FC5E53;font-size: 34rpx;">- ¥{{$count.mul(item.money||0, 1)}}</view>
			</view>
			<view class="priceRow">
				<text></text>
				<view style="font-size: 34rpx;"><text>合计：</text><text style="color: #FC5E53;">¥{{$count.mul(priceModel.realPay||0, 1)}}</text></view>
			</view>
		</view>
		<!-- 支付方式 -->
		<view class="payWay">
			<view class="jifen" v-if="payWayDict['incomesLocked']">
				<text>专项积分抵扣（可用{{ $count.mul(userInfo.incomesLocked||0, 1) }}）</text>
				<!-- <u-switch activeColor='#d4a781' v-model="isIncomesLocked" @change="paywayChange('isIncomesLocked')"></u-switch> -->
			</view>
			<view class="jifen" v-if="payWayDict['incomes']">
				<text>购物积分（可用{{$count.mul(userInfo.incomes||0, 1)}}）</text>
				<u-switch activeColor='#d4a781' v-model="isIncomes" @change="paywayChange('isIncomes')"></u-switch>
			</view>
			<view class="jifen" v-if="payWayDict['golds']">
				<text>金币（可用{{userInfo.golds}}）</text>
				<u-switch activeColor='#d4a781' v-model="isGolds" @change="paywayChange('isGolds')"></u-switch>
			</view>
			<view class="jifen" v-if="payWayDict['balance']">
				<text>现金余额（可用{{$count.mul(userInfo.balance||0, 1)}}）</text>
				<u-switch activeColor='#d4a781' v-model="isBalance" @change="paywayChange('isBalance')"></u-switch>
			</view>
			<view v-if="payWayDict['incomesLocked'] || payWayDict['incomes']"
			style="margin-left: 26rpx;color: #d4a781;font-size: 24rpx;margin-bottom: 10rpx;">提示：资产和微信支付不可叠加使用！</view>
		</view>
		<view style="background-color: #FFF;display: flex;flex-direction: row;align-items: center;justify-content: space-between;padding: 30rpx;border-top: 1px solid #EFEFEF;" v-if="payWayDict['wxpay']">
			<view style="display: flex;flex-direction: row;align-items: center;">
				<image style="width: 50rpx;height: 50rpx;margin-right: 20rpx;" src="/static/common/pay/luggage-pay-wechat.png"></image>
				<text>微信支付</text>
			</view>
			<u-switch activeColor='#d4a781' v-model="isWxpay" @change="paywayChange('isWxpay')"></u-switch>
		</view>
		<!-- 选择交付时间 -->
		<u-picker :show="delayDateShow" :columns="delayDateColumns" keyName='label' @cancel='delayDateShow = false' @confirm='delayDateConfirm'></u-picker>
		<view class="yunfei" style="margin-top: 10rpx;" v-if="activityKey == 'customGold'">
			<view @click="delayDateShow = true" style="width: 710rpx;display: flex;flex-direction: row;align-items: center;height: 100rpx;line-height: 100rpx;justify-content: space-between;color: #333;font-size: 34rpx;">
				<view style="margin-right: 12rpx;">选择交付时间</view>
				<view style="display: flex;flex-direction: row;align-items: center;">
					<text style="margin-right: 20rpx;font-weight: bold" v-if="delayDateValue.label">{{delayDateValue.label}}</text>
					<text style="margin-right: 20rpx;color: #999;" v-else>请选择</text>
					<u-icon name="arrow-right" color="#333" size="30rpx"></u-icon>
				</view>
			</view>
		</view>
		<!-- 留言 -->
		<view style="height: 80rpx;display: flex;flex-direction: row;align-items: center;background-color: #FFF;padding: 0rpx 30rpx;margin-top: 10rpx;">
			<text style="margin-right: 12rpx;">留言</text>
			<u--input v-model="itemModel.remark" placeholder="请备注大小颜色等~" border='none' maxlength='200'></u--input>
		</view>
		<!-- 提货方式 -->
		<view class="yunfei" style="margin-top: 10rpx;" v-if="expressage || isSelfPickup">
			<view style="width: 710rpx;display: flex;flex-direction: row;align-items: center;height: 100rpx;line-height: 100rpx;justify-content: flex-end;font-weight: bold;color: #333;font-size: 34rpx;" @click="sendWayHandle">
				<text style="margin-right: 20rpx;" v-if="expressage && isSelfPickup && sendType == ''">选择提货方式</text>
				<text style="margin-right: 20rpx;" v-else-if="expressage && sendType == 'expressage'">物流配送</text>
				<text style="margin-right: 20rpx;" v-else="isSelfPickup && sendType == 'selfPickup'">到店自提</text>
				<u-icon name="arrow-right" color="#333" size="30rpx"></u-icon>
			</view>
		</view>
		<view v-if="sendType == 'selfPickup'"  class="selfPickup" @click="selectSelfPickup">
			<view style="display: flex;flex-direction: row;align-items: center;" v-if="selfPickupInfo">
				<u-icon class='left' name="map" color='#d4a781'></u-icon>
				<view style="display: flex;flex-direction: column;margin-left: 10rpx;">
					<text>{{selfPickupInfo.name}}</text>
					<text style="color: #999;">{{selfPickupInfo.detailAddr}} </text>
					<!-- <text style="color: #999;"> 距离您1.34千米</text> -->
				</view>
			</view>
			<view style="color: #d4a781;display: flex;flex-direction: row;align-items: center;justify-content: center;" v-else>
				<u-icon name="plus" color="#d4a781" size="36rpx"></u-icon>
				<text style="margin-left: 20rpx;"></text>
			</view>
		</view>
		<addrInfo v-if="sendType == 'expressage'"  @click='selectAddrTap' :model='addrInfo'></addrInfo>
		
		<view class="readme" v-if="pageConfig.isShow2">
			<view class="left" @tap="read">
				<view :class="readmeActive?'':'no'"></view>
			</view>
			<view class="right">我已阅读并且同意<text @tap="goXY">《{{pageConfig.text1}}》</text></view>
		</view>
		<view style="margin-bottom: 160rpx;"></view>
		<!-- 购物车、支付 -->
		
		<goods-nav-bar>
			<view slot="button">
				<view style="color: #FC5E53;" v-if="activityKey=='incomesDeduction'">
					<text style="font-size: 40rpx;font-weight: bold;">¥{{ $count.mul(priceModel.realpay||0, 1) }}</text>
					<text style="font-size: 40rpx;font-weight: bold;">+</text>
					<text style="font-size: 40rpx;font-weight: bold;">{{ $count.mul(realpayIncomes||0, 1) }}积分</text>
				</view>
				<view v-else style="color: #FC5E53;font-size: 40rpx;font-weight: bold;">¥{{$count.mul(priceModel.realPay||0, 1)}}</view>
			</view>
			<view slot="button" style="margin-left: 40rpx;">
				<u-button @click='payTap' :custom-style='handleBtnPay' shape='circle'>去支付</u-button>
			</view>
		</goods-nav-bar>
		<u-action-sheet :actions="sendWayList" @select="selectSendWay" :show="sendWayShow" cancelText='取消' :closeOnClickOverlay="true" :closeOnClickAction="true" @close='sendWayShow = false'></u-action-sheet>
	</view>
</template>

<script>
	import {wxminiproPay} from '@/common/utils/wxminiproPay.js'
	import {user} from '@/api/user.js'
	import {addr} from '@/api/addr.js'
	import {order} from '@/api/order.js'
	import jcButton from "@/components/jc-button/jc-button.vue"
	import addrInfo from "@/components/addrInfo/addrInfo.vue"
	import goodsNavBar from '@/components/goodsNavBar/goodsNavBar.vue'
	import orderShopCartList from "@/pageA/order/components/orderShopCartList.vue"
	import {
		page
	} from '@/api/page.js'
	export default{
		components:{ jcButton, addrInfo, orderShopCartList, goodsNavBar },
		data() {
			return {
				scene: '',
				pageConfig: {},
				payWayDict: {},
				sendWayDict: {},
				type: 'item',
				readmeActive: true,
				orderId: '',
				groupId: '',
				addrInfo: {},
				selfPickupInfo: null,
				itemModel: {skuModel:{}},
				activityModel: {},
				activityKey: '',
				orderItemList: [],
				transportFee: 0,
				priceModel: {},
				realpayIncomes: 0,
				orderModel: {
					itemModel:{},
					orderStatus:''
				},
				shopId: '',
				delayDateShow: false, //延迟日期
				delayDateColumns: [],
				delayDateValue: {},
				sendType: '',
				isSelfPickup: false, //是否自提
				expressage: false, //是否物流
				isIncomes: false, //是否使用积分
				isIncomesLocked: false, //是否使用专项积分
				isGolds: false, //是否使用金币支付
				isBalance: false, //是否使用现金余额
				isWxpay: true,
				userInfo: {},
				currentPayway:0,
				sendWayShow: false,
				sendWayList: [{name:'物流配送', key: 'expressage'}, {name:'到店自提', key: 'selfPickup'}],
				handleBtnPay:{
					width: '200rpx',
					height: '80rpx',
					marginRight: '20rpx',
					fontSize: '26rpx',
					color: '#FFFFFF',
					backgroundColor: '#FC5E53'
				},
			}
		},
		//type
		//item 商品购买 
		//WIN 领取参团奖励
		//payGroupItem 购买参团奖励
		//bean 积分商品购买
		onLoad() {
			if(this.$Route.query){
				this.scene = this.$Route.query.scene
				this.shopId = this.$Route.query.shopId
				this.orderItemList = JSON.parse(decodeURIComponent(this.$Route.query.orderItemList))
				this.priceModel = JSON.parse(decodeURIComponent(this.$Route.query.priceModel))
				this.activityModel = this.$Route.query.activityModel ? JSON.parse(decodeURIComponent(this.$Route.query.activityModel)) : {}
				this.activityKey = this.activityModel.key
				this.realpayIncomes = this.$Route.query.realpayIncomes
			}
			this.getPageByClientname()
			this.findDefaultAddr()
		},
		onShow() {
			this.getUserInfo()
		},
		methods:{
			delayDateConfirm(val){
				this.delayDateShow = false
				this.delayDateValue = val.value[0]
			},
			scanAction() {
				let that = this
				uni.scanCode({
					success: function(res) {
						var params = that.$tools.urlParmasToObj(res.result)
						if (params.parentCode) {
							that.$set(that.itemModel, 'parentCode', params.parentCode)
						}
					}
				});
			},
			getPageByClientname() {
				page.getPageByClientname({
					name: this.$Route.name
				}).then(res => {
					if (res.data.code == 10000) {
						this.pageConfig = res.data.data
						// 设置支付方式
						this.payWayDict = this.$tools.paramsToObj(this.pageConfig.options1)
						if(!this.payWayDict['wxpay']){
							this.isGolds = true
						}else if(!this.payWayDict['golds'] && !this.payWayDict['wxpay']){
							this.isIncomes = true
						}
						// 设置配送方式
						this.sendWayDict = this.$tools.paramsToObj(this.pageConfig.options2)
						console.log('sendWayDict', this.sendWayDict['expressage'], this.sendWayDict['selfPickup'])
						if(this.sendWayDict['selfPickup']){
							this.isSelfPickup = true //仅自提
							this.sendType = 'selfPickup'
						}
						if(this.sendWayDict['expressage']){
							this.expressage = true //仅物流
							this.sendType = 'expressage'
						}
						// if(this.sendWayDict['expressage'] && !this.sendWayDict['selfPickup']){
						// 	this.expressage = true //仅物流
						// }else if((this.sendWayDict['selfPickup'] && !this.sendWayDict['expressage'])){
						// 	this.isSelfPickup = true //仅包
						// }
						this.setPageConfig(this.pageConfig)
						this.countTransportFeeAndRealpay()
					}
				})
			},
			setPageConfig(pageConfig){
				this.pageConfig = pageConfig
				uni.setNavigationBarTitle({
					title: this.pageConfig.title
				})
				uni.setNavigationBarColor({
					backgroundColor: this.pageConfig.background,
					frontColor: (!this.pageConfig.navigationBarBackground || this.pageConfig.navigationBarBackground =='#FFF' || this.pageConfig.navigationBarBackground =='#fff' || this.pageConfig.navigationBarBackground =='#FFFFFF' || this.pageConfig.navigationBarBackground =='#ffffff')  ? "" : "#ffffff"
				})
			},
			countTransportFeeAndRealpay(){
				// 如果商品为在线支付且用户选择物流配送,则计算快递费
				console.log('transportFee--', this.itemModel.isOnlinePay, this.expressage)
				if(this.itemModel.isOnlinePay && this.expressage){
					console.log('transportFee', this.transportFee)
					this.transportFee = this.$count.mul(this.itemModel.transportFee||0, 1)
				}
				this.priceModel.realPay = this.$count.add(this.priceModel.realPay||0, this.transportFee||0)
			},
			// 选择提货方式按钮
			sendWayHandle(){
				if(this.sendWayDict['expressage'] && this.sendWayDict['selfPickup']){
					this.sendWayShow = true
				}
			},
			//选择提货方式
			selectSendWay(e){
				console.log(e)
				if(e.key=='selfPickup'){
					this.sendType = 'selfPickup'
				}else if(e.key=='expressage'){
					this.sendType = 'expressage'
				}
				this.countTransportFeeAndRealpay()
			},
			//选择支付方式
			paywayChange(e){
				console.log("选择支付方式", e)
				// this.currentPayway = index
				
				switch (e){
					case 'isWxpay':
						this.isBalance = false
						this.isIncomes = false
						this.isIncomesLocked = false
						this.isGolds = false
						this.isWxpay = true
						break;
					case 'isGolds':
						this.isBalance = false
						this.isIncomes = false
						this.isIncomesLocked = false
						this.isGolds = true
						this.isWxpay = false
						break;
					case 'isIncomes':
						this.isBalance = false
						this.isGolds = false
						this.isWxpay = false
						break;
					case 'isIncomesLocked':
						this.isBalance = false
						this.isGolds = false
						this.isWxpay = false
						break;
					case 'isBalance':
						this.isIncomes = false
						this.isIncomesLocked = false
						this.isGolds = false
						this.isWxpay = false
						this.isBalance = true
						break;
					default:
						break;
				}
			},
			//去付款
			payTap(){
				if(this.sendType == 'expressage'){
					if(!this.addrInfo.id){
						uni.showToast({
							title: '请完善收货地址',
							icon: 'none'
						})
						return
					}
				}else if(this.sendType == 'selfPickup'){
					if(!this.selfPickupInfo){
						uni.showToast({
							title: '请选择自提点',
							icon: 'none'
						})
						return
					}
				}else{
					uni.showToast({
						title: '请选择提货方式',
						icon: 'none'
					})
					return
				}
				//参数
				var params = {
					shopId: this.shopId,
					remark: this.itemModel.remark,
					scene: this.scene
				}
				var tostContent = ''

				params.orderItemList = this.orderItemList

				if(this.isIncomes && this.isIncomesLocked){
					params.payway = 'incomeAndIncomeLocked'
				}else if(this.isIncomesLocked){
					params.payway = 'incomeLocked'
					tostContent = '本次支付将消耗'+this.priceModel.realPay + '锁定积分'
				}else if(this.isIncomes){
					params.payway = 'incomes'
					tostContent = '本次支付将消耗'+this.priceModel.realPay + '积分'
				}else if(this.isGolds){
					params.payway = 'golds'
				}else if(this.isBalance){
					params.payway = 'balance'
					tostContent = '本次支付将消耗'+this.priceModel.realPay + '现金余额'
				}else if(this.isWxpay){
					params.payway = 'wxpay'
				}else{
					this.$show.showMessage('请选择支付方式')
					return
				}
				console.log('pay', params.payway)
				if(this.sendType == 'selfPickup'){
					var addrInfo = {}
					addrInfo['name'] = this.selfPickupInfo.name
					addrInfo['contactName'] = this.selfPickupInfo.contactName
					addrInfo['contactPhone'] = this.selfPickupInfo.contactPhone
					addrInfo['addrInfo'] = this.selfPickupInfo.detailAddr
					params.sendType = 'selfPickup'
					params.addrinfo = JSON.stringify(addrInfo)
				}else if(this.sendType == 'expressage'){
					var addrInfo = {}
					addrInfo['contactName'] = this.addrInfo.contactName
					addrInfo['contactPhone'] = this.addrInfo.contactPhone
					addrInfo['addrInfo'] = this.addrInfo.addrInfo
					params.sendType = 'expressage'
					params.addrinfo = JSON.stringify(addrInfo)
				}
				if(this.isNeedParentCode && !this.itemModel.parentCode){
					this.$show.showMessage('请填写或扫码获取推荐人二维码')
					return
				}else{
					params.parentCode = this.itemModel.parentCode
				}
				if(!this.readmeActive){
					this.$show.showMessage('请阅读并同意'+this.pageConfig.text1)
					return
				}
				// if(this.userInfo.phone=='test'){
				// 	this.$show.showMessage('该活动商品暂未开启')
				// 	return
				// }
				switch (params.payway){
					case 'balance':
						var _this = this
						uni.showModal({
							content: tostContent,
							confirmText: '确定',
							cancelText: '取消',
							complete(_res) {
								if(_res.confirm){
									_this.wxminiproPay(params)
								}
							}
						})
						break;
					case 'wxpay':
						this.wxminiproPay(params)
						break;
					default:
						var _this = this
						uni.showModal({
							content: tostContent,
							confirmText: '确定',
							cancelText: '取消',
							complete(_res) {
								if(_res.confirm){
									_this.wxminiproPay(params)
								}
							}
						})
						break;
				}
			},
			wxminiproPay(params){
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				wxminiproPay(params).then(res => {
					uni.hideLoading()
					if(res.data.code == 10000){
						uni.showModal({
							content: '支付成功',
							confirmText: '确定',
							showCancel: false,
							complete(_res) {
								if(_res.confirm){
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
							}
						})
					}
				})
			},
			//选择地址
			selectAddrTap(){
				uni.navigateTo({
					url: '/pageA/addr/addrList'
				})
			},
			//填写地址回调方法
			selectAddrInfoBack(e){
				console.log('选择地址回调', e)
				var addrInfo = JSON.parse(decodeURIComponent(e))
				this.addrInfo = addrInfo
			},
			// 选择自提点
			selectSelfPickup(){
				this.$Router.push({
					name: 'addrOfSelfPickup',
					params: {
						shopId: this.shopId
					}
				})
			},
			// 选择自提点回调方法
			selectSelfPickupBack(e){
				var selfPickupInfo = JSON.parse(decodeURIComponent(e))
				this.selfPickupInfo = selfPickupInfo
			},
			getUserInfo() {
				user.getUserInfo().then(res => {
					if (res.data.code == 10000) {
						this.userInfo = res.data.data
						// 计算满减折扣
						var realPay = this.priceModel.sellingPrice
						var discountParams = []
						if(this.userInfo.incomesCredit>0){
							if(this.userInfo.incomesCredit < this.$count.mul(this.priceModel.sellingPrice, 0.1)){
								realPay = this.priceModel.sellingPrice - this.userInfo.incomesCredit
								discountParams.push({'type': '抵扣积分', 'money': this.userInfo.incomesCredit})
							}else{
								realPay = this.$count.mul(this.priceModel.sellingPrice, 0.9)
								discountParams.push({'type': '抵扣积分', 'money': this.$count.sub(this.priceModel.sellingPrice, realPay)})
							}
						}
						this.priceModel.realPay = realPay
						this.priceModel.discountParams = discountParams
							// if user.incomesCredit > 0:
							// 	if user.incomesCredit < sellingPrice * Decimal(0.1):
							// 		realPay = sellingPrice - user.incomesCredit
							// 		discountParams.append({'type': '抵扣积分', 'money': str(user.incomesCredit)})
							// 	else:
							// 		realPay = Decimal(sellingPrice * Decimal(0.9)).quantize(Decimal("0.00"))
							// 		discountParams.append({'type': '抵扣积分', 'money': str(Decimal(sellingPrice-realPay))})
							// else:
							// 	realPay = sellingPrice
							// }
						
					}
				})
			},
			//获取默认收货地址
			findDefaultAddr(){
				let that = this
				addr.findDefaultAddr().then(res => {
					if(res.data.code == 10000){
						var addrInfo = res.data.data
						addrInfo.addrInfo = addrInfo.area.replace(/，/g,' ') + '  ' + addrInfo.detailAddr
						that.addrInfo = addrInfo
					}
				})
			},
			//提示先阅读服务协议
			readmeTap(){
				uni.showModal({
					content: '请先阅读并同意' + this.pageConfig.text1,
					confirmText: '确定',
					showCancel: false
				})
			},
			//跳转到服务协议
			goXY(){
				this.$Router.push({
					name: 'protocolView',
					params:{
						content: this.pageConfig.longtext
					}
				})
			},
			//已阅读服务协议
			read(){
				this.readmeActive = !this.readmeActive
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container{
		padding-top: 20rpx;
		padding-bottom: 60rpx;
	}
	.priceRow{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 26rpx;
	}
	.selfPickup{
		min-height: 90rpx;
		background-color: #ffffff;
		padding-left: 20rpx;
	}
	.item{
		margin-top: 10rpx;
	}
	.payWay{
		display: flex;
		flex-direction: column;
		margin-top: 10rpx;
		background-color: #FFFFFF;
		.jifen{
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			padding: 30rpx 30rpx;
			text-align: right;
		}
		.totalPrice{
			padding: 40rpx;
			text-align: right;
			background-color: #FFFFFF;
			text:nth-of-type(2){
				color: #FC5E53;
				font-size: 34rpx;
				font-weight: bold;
			}
			text:nth-of-type(3){
				font-size: 24rpx;
			}
		}
	}
	.yunfei{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		margin-top: 8rpx;
		padding: 0rpx 30rpx;
		text-align: right;
		background-color: #FFFFFF;
	}
	.orderInfo{
		background-color: #FFFFFF;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		color: #999999;
		font-size: 24rpx;
		padding: 30rpx
	}
	.readme{
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 40upx;
		margin-left: 30rpx;
		.left{
			width: 21upx;
			height: 21upx;
			background-color: #fff;
			border-radius: 50%;
			border: 1px solid #d4a781;
			margin-right: 19upx;
			display: flex;
			align-items: center;
			justify-content: center;
			view{
				width: 12upx;
				height: 12upx;
				border-radius: 50%;
				background-color: #d4a781;
			}
			.no{
				background-color: #FFF;
			}
		}
		.right{
			font-size: 26rpx;
			color: #999;
			text{
				color: #d4a781;
			}
		}
	}
</style>
